import { fetchList, fetchView, store } from './api'

export default {
  namespaced: true,
  state: () => ({
    list: [],
    total: 0,
    count: 0,
    detail: []
  }),
  getters: {
    list (state) {
      return state.list
    },
    total (state) {
      return state.total
    },
    count (state) {
      return state.count
    }
  },
  actions: {
    async fetchList ({ commit }, params) {
      const { id, ...r } = params
      const { data } = await fetchList(id, r)
      commit('SET_LIST', data)
    },
    async fetchView ({ commit }, id) {
      const { data } = await fetchView(id)
      commit('SET_DETAIL', data)
    },
    async store ({ commit }, params) {
      const { item_id, ...r } = params
      const { data } = await store(item_id, r)
      commit('SET_REPLY', data)
    }
  },
  mutations: {
    SET_LIST (state, payload) {
      state.list = payload.data
      state.total = payload.meta.total
      state.count = payload.meta.count
    },
    SET_DETAIL (state, payload) {
      state.detail = payload.data
    },
    SET_REPLY (state, payload) {
      const { list, total, count } = state
      const { data } = payload
      if (data.parent_id) {
        const index = list.findIndex(({ id }) => id === data.parent_id)
        list[index].children.push(data)
      } else {
        list.push(data)
        state.total = total + 1
      }
      state.count = count + 1
      state.list = list
    }
  }
}
